package com.syt.sms.controller;

import com.syt.result.Result;
import com.syt.sms.service.SMSService;
import com.syt.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: xxx
 * @Date: 2023/2/24 19:49
 * @Description: 手机短信服务接口
 */
@Api(tags="手机短信服务")
@RestController
@RequestMapping("/api/sms")
public class SMSApiController {

    @Autowired
    private SMSService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //TODO 接口防止被刷
    @ApiOperation(value = "发送手机短信")
    @GetMapping("/send/{phone}")
    public Result sendCodeByPhone(@PathVariable String phone){
        //从redis获取验证码，如果获取到，返回ok
        //redis key是手机号码 value是验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }

        //若从redis获取不到手机验证码，
        // 则生成六位验证码，通过手机短信服务进行发送
        code= RandomUtil.getSixBitRandom();//六位验证码
        boolean isSend= smsService.sendCodeByPhone(phone, code);
         //生成的验证码放到redis里面，设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
           return Result.ok();
        }else {
          return Result.fail().message("发送手机短息失败");
        }

    }


}
